﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mls;
using Mls.IO;
using System.IO;
using Mls.Interpreters;

namespace TestApplication
{
    /*class Interpreter : Mls.Interpreters.IMlsInterpreter
    {
        #region IMlsInterpreter Members

        public void StartHeader()
        {
            Console.WriteLine("[Start Header]");
        }

        public void EndHeader()
        {
            Console.WriteLine("[End Header]");
        }

        public void StartFooter()
        {
            Console.WriteLine("[Start Footer]");
        }

        public void EndFooter()
        {
            Console.WriteLine("[End Footer]");
        }

        public void StartFontTable()
        {
            throw new NotImplementedException();
        }

        public int AddFont(Language.Type language, string fontFamily, string fontName)
        {
            throw new NotImplementedException();
        }

        public void EndFontTable()
        {
            throw new NotImplementedException();
        }

        public void StartDocument()
        {
            Console.WriteLine("[Start Document]");
        }

        public void EndDocument()
        {
            Console.WriteLine("[End Document]");
        }

        public void EndParagraph()
        {
            Console.WriteLine("[End Paragraph]");
        }

        public void StartFootnote()
        {
            Console.Write("[Start Footnote]");
        }

        public void EndFootnote()
        {
            Console.Write("[End Footnote]");
        }

        public void StartTable(ColumnDefinition[] columns)
        {
            Console.WriteLine("[Start Table: {0} columns]", columns.Length);
        }

        public void StartRow()
        {
            Console.Write("[Start Row]");
        }

        public void StartCell()
        {
            Console.Write("[Start Cell]");
        }

        public void EndCell()
        {
            Console.Write("[End Cell]");
        }

        public void EndRow()
        {
            Console.WriteLine("[End Row]");
        }

        public void EndTable()
        {
            Console.WriteLine("[End Table]");
        }

        public bool BoldFace
        {
            set { Console.Write("[Bold: {0}]", value); }
        }

        public bool Underline
        {
            set { Console.Write("[Underline: {0}]", value); }
        }

        public bool Strike
        {
            set { Console.Write("[Strike: {0}]", value); }
        }

        public Language.Type Language
        {
            set { Console.Write("[Language: {0}]", value); }
        }

        public void SetFont(Language.Type language, int fontId)
        {
            Console.Write("[Set font: lang {0}, id {1}]", language, fontId);
        }

        public void InsertPageBreak()
        {
            Console.WriteLine("[Page Break]");
        }

        public void InsertPageNumber()
        {
            Console.Write("[Page Number]");
        }

        public void InsertText(string text)
        {
            Console.Write(text);
        }

        public void SkippedCommand(string content)
        {
            Console.Write("[Command Skipped: '{0}']", content);
        }

        public void StartParagraph(Smartee.RichText.Justification justification, Smartee.RichText.TextDirection textDirection)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IMlsInterpreter Members


        public void ChangeLanguage(Language.Type language)
        {
            throw new NotImplementedException();
        }

        #endregion
    }*/

    class Program
    {
        private const string DocumentsPath = @"..\..\..\..\_MlsApplication\disk\doc";
        private const string TestDocumentPath = @"..\..\..\..\_Tests\TEST";

        /*static void Main(string[] args)
        {
            string[] files = new string[] { @"C:\Mls\disk\doc\A1", @"C:\Mls\disk\doc\A2", @"C:\Mls\disk\doc\A3", @"C:\Mls\disk\doc\A4", @"C:\Mls\disk\doc\A5", @"C:\Mls\disk\doc\A6", @"C:\Mls\disk\doc\A7" }; // Directory.GetFiles(@"C:\MLS\disk\doc\");

            Rtf.Writer rtf = new Rtf.Writer(new StreamWriter(@"C:\Mls\Mls.rtf"), new Rtf.Writer.Font[] { });

            foreach (string file in files)
            {
                rtf.StartParagraph(Rtf.Writer.Justify.Left, 0, 0, 0);
                rtf.InsertContent("File: " + file);
                rtf.EndParagraph();
                rtf.StartParagraph(Rtf.Writer.Justify.Left, 0, 0, 0);

                Console.WriteLine("Reading file: {0}", file);

                try
                {
                    Reader reader = new Reader(new BinaryReader(File.OpenRead(file)));
                    while (true)
                    {
                        Character character = reader.Read();
                        if (character.Type == Token.EndOfFile)
                            break;

                        if (character.Type == Token.NewLine)
                        {
                            rtf.EndParagraph();
                            rtf.StartParagraph(Rtf.Writer.Justify.Left, 0, 0, 0);
                        }
                        else
                        {
                            string s = CharactersMapper.Map(character);
                            foreach (char x in s)
                            {
                                if (x < '\x100')
                                    rtf.InsertContent(x.ToString());
                                else

                                    rtf.InsertUnicodeCharacter(x);
                            }
                        }
                    }

                    Console.WriteLine("Successful");
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Error: {0}", exception.Message);
                    rtf.InsertContent(exception.Message);
                }

                rtf.EndParagraph();
            }

            Console.ReadKey();

            rtf.Close();

            Process.Start(@"C:\Mls\Mls.rtf");
        }*/

        /*static void Main(string[] args)
        {
            string[] errors;
            DocumentsChain[] chains = DirectoryChainFinder.Find(@"K:\Projects\Mls\disk\doc", out errors, Language.LanguageSettings.Default);
            Interpreter writer = new Interpreter();

            //Console.WriteLine("{0} errors", errors.Length);

            //foreach (string error in errors)
                //Console.WriteLine(error);

            //Console.WriteLine("");
            //Console.WriteLine("Chains:");

            bool skip = false;

            foreach (DocumentsChain chain in chains)
            {
                foreach (Document doc in chain.Documents)
                {
                    if (doc.Name == "AAP")
                    {
                        skip = false;
                        continue;
                    } || doc.Name == "AAM" || doc.Name == "AAM1" || doc.Name == "AAM2" ||
                        doc.Name == "AAN" || doc.Name == "AAP"
                    if (doc.Name != "A1")
                        continue;

                    Console.WriteLine("===================================================================");
                    Console.WriteLine(doc.Name);
                    Console.WriteLine("===================================================================");

                    StreamWriter stream = new StreamWriter(File.OpenWrite(@"C:\Users\Bishoy\Desktop\MLS\" + doc.Name + ".txt"));
                    stream.Write(doc.OriginalText);
                    stream.Close();

                    //try
                    //{
                    Smartee.RichText.VisitorAndBuilder.Builder builder = new Smartee.RichText.VisitorAndBuilder.Builder();
                    RichTextInterpreter interp = new RichTextInterpreter(builder);
                    interp.AddFont(Language.Type.Arabic, "swiss", "Tahoma");
                    interp.AddFont(Language.Type.Latin, "swiss", "Arial");
                    interp.AddFont(Language.Type.Coptic, "swiss", "Arial");
                    interp.AddFont(Language.Type.Greek, "swiss", "Arial");
                    doc.ParseDocument(interp);
                    builder.Document.Accept(new Smartee.RichText.VisitorAndBuilder.RtfWriter(new StreamWriter(@"C:Users\Bishoy\Desktop\test.rtf")));
                    //}
                    //catch (Exception exception)
                    //{
                        //Console.WriteLine("Error in {0}: '{1}'", doc.Name, exception.Message);
                    //}
                }

                //chain.Parse(writer);
            }
        }*/
        
        /*static void Main(string[] args)
        {
            Smartee.RichText.VisitorAndBuilder.Builder builder = new Smartee.RichText.VisitorAndBuilder.Builder();

            builder.StartDocument();
            builder.StartFontTable();
            int coptic = builder.AddFont("swiss", "ArialCoptic");
            int arial = builder.AddFont("swiss", "arial");
            builder.EndFontTable();
            builder.StartHeader();
            builder.StartParagraph(Smartee.RichText.Justification.Center, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("This is a test document");
            builder.EndParagraph();
            builder.EndHeader();
            builder.StartParagraph(Smartee.RichText.Justification.Center, Smartee.RichText.TextDirection.LeftToRight);
            builder.BoldFace = true;
            builder.Underline = true;
            builder.FontId = arial;
            builder.InsertText("Test Doc");
            builder.EndParagraph();
            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.FontId = arial;
            builder.InsertText("I cannot\tsee why");
            builder.StartFootnote("1");
            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("What\r\nare {S} you\\ talking about?");
            builder.EndParagraph();
            builder.EndFootnote();
            builder.InsertText(" you can't go there! \x2725");
            builder.EndParagraph();

            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.FontId = coptic;
            builder.InsertText("\x2C80\x2CEA \x2CE5 \x2C81\x2C81\x305\x2C81\x305\x2C81 \x2C80\x2C80\x2CF1\x2C80\x2CF0\x2C80\x2CF1\x2C80\x2CF0\x2C80 \x2C80\x2C80\x2CF1\x2C80\x2CEF\x2C80\x2CEF\x2C80\x2CF0\x2C80");
            builder.EndParagraph();

            builder.StartTable(Smartee.RichText.TextDirection.LeftToRight, new int[] { 3000, 5000, 3000 });
            builder.StartRow();

            builder.StartCell();
            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("Cell Text");
            builder.EndParagraph();
            builder.EndCell();

            builder.StartCell();
            builder.StartParagraph(Smartee.RichText.Justification.Center, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("Cell Text");
            builder.EndParagraph();
            builder.EndCell();

            builder.StartCell();
            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("Cell Text");
            builder.EndParagraph();
            builder.EndCell();

            builder.EndRow();

            builder.StartRow();

            builder.StartCell();
            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("Cell Text");
            builder.EndParagraph();
            builder.EndCell();

            builder.StartCell();
            builder.StartParagraph(Smartee.RichText.Justification.Center, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("Cell Text");
            builder.EndParagraph();
            builder.EndCell();

            builder.StartCell();
            builder.StartParagraph(Smartee.RichText.Justification.Left, Smartee.RichText.TextDirection.LeftToRight);
            builder.InsertText("Cell Text");
            builder.EndParagraph();
            builder.EndCell();

            builder.EndRow();

            builder.EndTable();

            Smartee.RichText.Document rtfDoc = builder.EndDocument();

            string file = @"C:\Documents and Settings\bishoyb\Desktop\test.rtf";

            rtfDoc.Accept(new Smartee.RichText.VisitorAndBuilder.RtfWriter(new StreamWriter(file)));

            System.Diagnostics.Process.Start(file);
        }*/

        static void Main(string[] args)
        {
            string file = TestDocumentPath; //Path.Combine(DocumentsPath, "A1");
            string target = Path.GetTempFileName();

            Document document = new Document(file, Language.LanguageSettings.Default);

            WriteDocumentToFile(document, target);

            string newName = Path.ChangeExtension(target, "RTF");
            File.Move(target, newName);
            System.Diagnostics.Process.Start(newName);
        }

        static void WriteDocumentToFile(Document mlsDoc, string targetFile)
        {
            Smartee.RichText.VisitorAndBuilder.Builder builder = new Smartee.RichText.VisitorAndBuilder.Builder();
            RichTextInterpreter interp = new RichTextInterpreter(builder);
            interp.AddFont(Language.Type.Arabic, "swiss", "Tahoma");
            interp.AddFont(Language.Type.Arabic, "swiss", "Tahoma");
            interp.AddFont(Language.Type.Arabic, "swiss", "Tahoma");
            interp.AddFont(Language.Type.Arabic, "swiss", "Tahoma");
            interp.AddFont(Language.Type.Latin, "swiss", "Arial");
            interp.AddFont(Language.Type.Coptic, "swiss", "ArialCoptic");
            interp.AddFont(Language.Type.Coptic, "swiss", "ArialCoptic");
            interp.AddFont(Language.Type.Coptic, "swiss", "ArialCoptic");
            interp.AddFont(Language.Type.Coptic, "swiss", "ArialCoptic");
            interp.AddFont(Language.Type.Coptic, "swiss", "ArialCoptic");
            interp.AddFont(Language.Type.Greek, "swiss", "Arial");
            Parser parser = new Parser(interp);
            parser.Parse(mlsDoc);
            builder.Document.Accept(new Smartee.RichText.VisitorAndBuilder.RtfWriter(new StreamWriter(targetFile)));
        }

        /*static void Main(string[] args)
        {
            BinaryReader reader = new BinaryReader(File.OpenRead(@"C:\Personal\Projects\MLS\disk\doc\A1"));
            byte[] header = reader.ReadBytes(0x190);
            reader.Close();

            BinaryWriter writer = new BinaryWriter(File.OpenWrite(@"C:\Personal\Projects\MLS\TEST"));
            writer.Write(header);

            for (byte language = 0; language < 4; language++)
            {
                if (language > 0)
                {
                    writer.Write(Character.NewLine.Encoded[0]);
                    writer.Write(Character.NewLine.Encoded[0]);
                    writer.Write(Character.NewLine.Encoded[0]);
                    writer.Write(Character.NewLine.Encoded[0]);
                    writer.Write(Character.NewLine.Encoded[0]);
                    writer.Write(Character.NewLine.Encoded[0]);
                }

                for (ushort accent = 1; accent < 31; accent++)
                {
                    if (accent > 1)
                        writer.Write(Character.Encode(0x20, language, Flags.None));
                    writer.Write(Character.Encode(language == 1? (byte)'H' : (byte)'a', language, Flags.Accented));
                    writer.Write((ushort)(accent << 10));
                }

                writer.Write(Character.NewLine.Encoded[0]);
                writer.Write(Character.NewLine.Encoded[0]);
                writer.Write(Character.Encode(language == 1 ? (byte)'H' : (byte)'a', language, Flags.Accented));
                writer.Write((ushort)((1 << 10) + (2 << 5)));
                writer.Write(Character.Encode(0x20, language, Flags.None));
                writer.Write(Character.Encode(language == 1 ? (byte)'H' : (byte)'a', language, Flags.Accented));
                writer.Write((ushort)((1 << 10) + (2 << 5) + 3));
                writer.Write(Character.NewLine.Encoded[0]);

                for (byte raw = 0x21; raw < 0xFF; raw++)
                {
                    if (raw % 0x10 == 1)
                        writer.Write(Character.NewLine.Encoded[0]);
                    else
                        writer.Write(Character.Encode(0x20, language, Flags.None));

                    writer.Write(Character.Encode(raw, language, Flags.None));

                    Console.WriteLine("Writing Character 0x{0:X2} Language {1}", raw, language);
                }

                writer.Write(Character.Encode(0x20, language, Flags.None));
                writer.Write(Character.Encode(0xFF, language, Flags.None));
            }
            writer.Close();
        }*/
    }
}
